package cn.itcast.bos.web.action.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;
@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven{
	//模型驱动
  private Standard standard = new Standard();
	@Override
	public Standard getModel() {
		this.standard = standard;
		return standard;
	}
	//调用Service层
	@Resource(name="standardServiceImpl")
	private StandardService standardService;
	//保存数据
	@Action(value="standard_save",results={@Result(name="success",type="redirect",location="./pages/base/standard.html")})
  public String save(){
	  standardService.save(standard);
	  return SUCCESS;
  }
	//属性驱动
	private int page;
	private int rows;
     public void setPage(int page) {
		this.page = page;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	//分页查询
	@Action(value="standard_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		//spring为分页查询提供的实现类
		PageRequest pageRequest = new PageRequest(page-1,rows);
		Page<Standard> page = standardService.pageQuery(pageRequest);
		//返回客户端需要分页查询的数据
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("total", page.getTotalElements());
		map.put("rows", page.getContent());
		//将map 数据转换成json数据压入valuestack值栈顶部返回给页面，由struts2-json-plugin处理数据即可
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	//收排标准查询
	@Action(value="standard_findAll",results={@Result(name="success",type="json")})
	public String findAll(){
		//spring为分页查询提供的实现类
		List<Standard> list = standardService.findAll();
		//将数据压入值栈顶部，转换成json数据
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
}
